package com.dq.controller.api.merchant.my;

import com.dq.cache.J2CacheUtils;
import com.dq.context.event.user.UserEditPhoneEvent;
import com.dq.exception.customException.AdminException;
import com.dq.controller.api.merchant.in.request.EditBossUser;
import com.dq.controller.api.merchant.in.request.EditPhoneRequest;
import com.dq.controller.api.merchant.in.request.EditPwdRequest;
import com.dq.controller.api.merchant.in.template.AreaTreeBuilder;
import com.dq.controller.in.user.BossUserQuery;
import com.dq.vo.Vo;
import com.dq.domain.address.NullSysRegion;
import com.dq.domain.address.SysRegion;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import com.dq.utils.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author liuhui
 * @date 2019/12/3 0003 10:41:37
 */
@RestController
@RequestMapping("/api/boss")
@Api(description = "boss 子账号/区域/个人信息修改")
public class ApiUserController extends AllService {

    @Value("${oss-show-url}")
    private String ossShowUrl;

    @PostMapping("/bossAccount/list")
    @ApiOperation("boss子账户列表")
    public Vo bossAccountList(@RequestBody BossUserQuery bossAccountQuey)throws AdminException {
        bossAccountQuey.format();
        List<BossUser> bossUserList = bossUserService.list(bossAccountQuey);
        Long totalCount = bossUserService.count(bossAccountQuey);
        List<Map> mapList = new ArrayList<>();
        bossUserList.forEach(bossUser -> {
            Map map = new HashMap();
            map.put("id",bossUser.getId());
            map.put("userRealCName",bossUser.getUserRealcName());
            map.put("username",bossUser.getUsername());
            map.put("statusCn",bossUser.getStatus().name);
            map.put("statusEn",bossUser.getStatus());
            mapList.add(map);
        });
        PageInfo pageInfo = new PageInfo(mapList);
        pageInfo.setTotal(totalCount);
        return new Vo(pageInfo);
    }

    @PostMapping("/bossAccount/add")
    @ApiOperation("boss子账户添加")
    public Vo bossAccountAdd(@RequestBody BossUser bossUserAdd) throws AdminException {
        bossUserService.saveBossUserSon(bossUserAdd);

        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/bossAccount/edit/{id}")
    @ApiOperation("boss子账户整体信息修改/状态修改")
    public Vo bossAccountEdit(@PathVariable Long id, @ApiParam("状态修改 只传status（off：禁用), on:正常）") @RequestBody BossUser bossUserEdit)throws AdminException {
        BossUser bossUser = dao.get(BossUser.class,id);
        if(null==bossUser){throw new AdminException("子账户信息不存在");}
        BeanUtils.copyProperties(bossUserEdit,bossUser, BeanNullUtil.getNullPropertyNames(bossUserEdit));
        if(StringUtils.isNotEmpty(bossUserEdit.getPassword())){
            bossUser.setPassword(sysUserService.getPassword( bossUser.getPassword()));
        }
        bossUserRepository.save(bossUser);
        return new Vo(HttpStatus.OK);
    }
    @ApiOperation("boss子账户删除")
    @PostMapping("/bossAccount/delete/{userId}")
    public Vo delete(@PathVariable @ApiParam(value = "用户id") Long userId) throws AdminException {
        if (userId == 1) {
            throw new AdminException("系统管理员不能被删除");
        }
        if (userId.equals(shiroService.getUserId())) {
            throw new AdminException("不能删除登录账号");
        }
        BossUser bossUser = dao.get(BossUser.class, userId);
        if(bossUser == null) {
            throw new AdminException("无对应账户");
        }
        bossUser.setDeleted(true);

        bossUserService.update(bossUser);
        return new Vo(HttpStatus.OK);
    }

    @GetMapping("/bossAccount/detail/{id}")
    @ApiOperation("boss子账户详情查看")
    public Vo bossAccountDetail(@PathVariable Long id)throws AdminException {
        BossUser bossUser = dao.get(BossUser.class,id);
        if(null==bossUser){throw new AdminException("子账户信息不存在");}
        return new Vo(bossUser.toVO(false));
    }

    @PostMapping("/area/list")
    @ApiOperation("区域列表")
    public Vo areaList(){
        List<SysRegion> sysRegions = sysRegionRepository.findAll();
        Set<SysRegion.Vo> sysRegionVo = new HashSet<>();
        sysRegions.forEach(sysRegion -> {
            sysRegionVo.add((SysRegion.Vo) sysRegion.toVO(false));
        });
        List<SysRegion.Vo> voList = AreaTreeBuilder.getRegionTree(sysRegionVo);
        PageInfo pageInfo = new PageInfo(voList);
        return new Vo(pageInfo);
    }

    @PostMapping("/area/root/add")
    @ApiOperation("添加根节点区域")
    public Vo areaRootAdd(@RequestBody SysRegion sysRegion){
        NullSysRegion nullSysRegion = (NullSysRegion) J2CacheUtils.get("NullSysRegion");
        sysRegion.setParent(nullSysRegion);
        sysRegionRepository.save(sysRegion);
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/area/child/add/{parentId}")
    @ApiOperation("添加区域子节点")
    public Vo areaChildAdd(@PathVariable Long parentId, @RequestBody SysRegion sysRegionAdd)throws AdminException {
        SysRegion parent = dao.get(SysRegion.class,parentId);
        SysRegion sysRegion = sysRegionRepository.findByParentAndName(parent,sysRegionAdd.getName());
        if(null!=sysRegion){throw new AdminException("该地区已存在");}
        sysRegionAdd.setParent(parent);
        sysRegionRepository.save(sysRegionAdd);
        return new Vo(HttpStatus.OK);
    }


    @PostMapping("/userHonorWallImgEdit/{userId}")
    @ApiOperation("boss用户像修改/上传")
    public Vo userHonorWallImgEdit(@PathVariable Long userId , @ApiParam(value = "用户荣誉墙头像上传") MultipartFile file)throws IOException, AdminException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(!EditCheckUtil.isImage(suffix)){throw new AdminException("图片格式不正确");}
        BossUser bossUser = (BossUser) shiroService.getUser();
        if(null==bossUser){throw new AdminException("未登录");}
        String fileName = ossService.upload(FileUtil.save(file));
        bossUser.setHeadImg(ossShowUrl+fileName);
        bossUserRepository.save(bossUser);
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/editPwd")
    @ApiOperation("修改当前登陆人密码")
    public Vo editPwd(@RequestBody EditPwdRequest editPwdRequest)throws AdminException {
        BossUser bossUser = (BossUser) shiroService.getUser();
        if(!PasswordUtil.verify(editPwdRequest.getOldPwd(),bossUser.getPassword())){throw new AdminException("旧密码不正确");}
        bossUser.setPassword(sysUserService.getPassword(editPwdRequest.getNewPwd()));
        BossUser newUser= bossUserRepository.save(bossUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @PostMapping("/editPhone/sendSms")
    @ApiOperation("修改当前用户手机号发送验证码")
    public Vo editPhoneSendSms() throws AdminException {
        BossUser bossUser = (BossUser)shiroService.getUser();
        if(StringUtils.isEmpty(bossUser.getMobile())){
            throw new AdminException("请先绑定手机号");
        }
        String smsCode = RandomUtil.getNumber(6);
        Map<String, Object> map = new HashMap<>();
        map.put("phone", bossUser.getMobile());
        map.put("smsCode", smsCode);
        eventPublisher.publishEvent(new UserEditPhoneEvent(map));
        shiroService.setSmsCaptchaCache(smsCode,bossUser.getMobile());
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("/editPhone")
    @ApiOperation("修改当前用户手机号")
    public Vo editPhone(@RequestBody EditPhoneRequest editPhoneRequest)throws AdminException {
        if(!EditCheckUtil.isMobileNO(editPhoneRequest.getPhone())){throw new AdminException("手机号格式不正确");}
        String cacheSms = shiroService.getSmsCaptchaCache(editPhoneRequest.getPhone());
        if(!cacheSms.equals(editPhoneRequest.getSmdCode())){throw new AdminException("验证码不正确");}
        BossUser bossUser = (BossUser) shiroService.getUser();
        bossUser.setUsername(editPhoneRequest.getPhone());
        BossUser newUser= bossUserRepository.save(bossUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @GetMapping("/editNickName/{nickName}")
    @ApiOperation("修改昵称")
    public Vo editNickName(@PathVariable String nickName)throws AdminException {
        BossUser bossUser = (BossUser)shiroService.getUser();
        bossUser.setLocalNickName(nickName);
        BossUser newUser= bossUserRepository.save(bossUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @PostMapping("/userImgEdit")
    @ApiOperation("用户头像修改")
    public Vo userImgEdit(@ApiParam(value = "用户图片") MultipartFile file)throws IOException, AdminException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if(!EditCheckUtil.isImage(suffix)){throw new AdminException("图片格式不正确");}
        BossUser bossUser = (BossUser)shiroService.getUser();
        String fileName = ossService.upload(FileUtil.save(file));
        bossUser.setHeadImg(ossShowUrl+fileName);
        BossUser newUser= bossUserRepository.save(bossUser);
        tokenService.deleteToken(shiroService.getToken());
        newUser.setHeadImg(ossShowUrl+fileName);
        return new Vo(loginTemplate.toLogin(newUser));
    }

    @ApiOperation("boss用户信息修改")
    @PostMapping("/updateBossUser")
    public Vo updateBossUser(@RequestBody EditBossUser editBossUser) throws AdminException {
        if(editBossUser.getId() == null){
            throw new AdminException("请重新选择");
        }
        BossUser bossUser = dao.get(BossUser.class,editBossUser.getId());
        if(StringUtils.isNotEmpty(editBossUser.getNickName())){
            bossUser.setLocalNickName(editBossUser.getNickName());
        }
        if(StringUtils.isNotEmpty(editBossUser.getMobile())){
            SysUser byMobile = sysUserRepository.findByUsername(editBossUser.getMobile());
            if(byMobile != null){
                throw new AdminException("此手机号已存在");
            }
            bossUser.setUsername(editBossUser.getMobile());
        }
        BossUser newUser = bossUserRepository.save(bossUser);
        tokenService.deleteToken(shiroService.getToken());
        return new Vo(loginTemplate.toLogin(newUser));
    }

}
